<?php
namespace hwapp\controllers;

use app\models\EcsUsers;
use app\models\lib\AuthLib;
use app\models\TDetectionCalibration;
use app\models\TDetectionHeartrate;
use app\models\TDetectionOvulation;
use app\models\TDetectionPregnant;
use app\models\TDetectionUrine;
use app\models\TDeviceProcedure;
use backend\modules\shipping\models\EcsRegion;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;

/**
 * Site controller
 */
class SitesController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndexx()
    {
        header('Access-Control-Allow-Origin:*');
        $r = EcsUsers::find()->asArray()->limit(5)->all();
        print_r(json_encode($r));exit;
        return $this->render('index');
    }

    public function actionNiaoj()
    {
        header('Access-Control-Allow-Origin:*');
        $re = TDetectionCalibration::find()->limit(77)->asArray()->all();
        print_r(json_encode([true,$re]));exit;
    }

    public function actionBanben()
    {
        header('Access-Control-Allow-Origin:*');
        $re = TDeviceProcedure::find()->limit(1)->orderBy(['num' => SORT_DESC])->asArray()->one();
        return json_encode([true,$re['num']]);
    }

    public function actionTdevpro()
    {
        header('Access-Control-Allow-Origin:*');
        $re = TDeviceProcedure::find()->limit(1)->orderBy(['num'=>SORT_DESC])->asArray()->one();
//        $re['fileData'] = file_get_contents( 'http://120.77.60.169/xiaopu'.$re['url']);
//        $str = file_get_contents('http://120.77.60.169/xiaopu/upload/fileDeviceProcedure/xpDest_21514513081176.bin');
//        $str = file_get_contents('http://120.77.60.169/xiaopu/upload/fileDeviceProcedure/TPAD_MEILI-2.2(1)1529045891969.bin');
//        $str = file_get_contents('http://www.pooai.cn/wx/hwapp/web/TPAD-2.3.bin');
//        $str = file_get_contents('http://120.77.60.169/xiaopu/upload/fileDeviceProcedure/TPAD-2.31527060835095.bin');
//        $str = file_get_contents('http://120.78.225.35:8080/xiaopu/upload/fileDeviceProcedure/TPAD-2.3(1)1529917207086.bin');
        $str = file_get_contents('http://120.77.60.169/xiaopu'.$re['url']);
        $len = strlen($str);
        $bytes = array();
        for($i=0;$i<$len;$i++) {
            if(ord($str[$i]) >= 128){
                $byte = ord($str[$i]) - 256;
            }else{
                $byte = ord($str[$i]);
            }
            if($byte<0) {
                $byte = $byte & 0xff;
            }
            $bytes[] =  $byte ;
        }
        $re['fileData'] = $bytes;
        print_r(json_encode([true,$re]));exit;
    }
    public $enableCsrfValidation = false;
    //用户设置
    public function actionSetuser()
    {
        header('Access-Control-Allow-Origin:*');

        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr){
            $ecsuser = new EcsUsers();
            $userArr = EcsUsers::find()->where(['open_id'=>$PostArr['userid']])->asArray()->one();
            if($userArr){

            }else{
                $ecsuser->open_id = $PostArr['userid'];
                $ecsuser->user_name = $PostArr['username'];
                $ecsuser->login_type = 3;
                if($ecsuser->open_id){
                    if(!$ecsuser->save()) {
                        print_r($ecsuser->errors);exit;
                    }
                }
            }
        }
    }

    public function actionOvlation()
    {
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr){
            $userid = EcsUsers::findOne(['open_id'=>$PostArr['userid']])->user_id;
            $reArr = TDetectionOvulation::find()->where(['user_id'=>$userid])->asArray()->limit(3)->orderBy(['create_time'=>SORT_DESC])->all();
        }
        return json_encode($reArr);
    }

    public function actionSetovlation()
    {
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr) {
            $userid = EcsUsers::findOne(['open_id' => $PostArr['userid']])->user_id;
            $model = new TDetectionOvulation();
            $model->user_id = $userid;
            $model->group_date = date("Y-m-d",time());
            $model->category = "排卵检测";
            $model->ovu = (int)$PostArr['DetectionResult'];
            if($model->ovu==0)
                $model->result = '未排卵';
            else  if($model->ovu==1)
                $model->result = '已排卵';
            else
                $model->result = '检测错误';
            $model->source_data = '检测数据';
            $model->create_time = date("Y-m-d H:i:s",time());
            $model->status = 1;
            if(!$model->save()){
                print_r($model->errors);exit;
            }
            return json_encode([true]);
        }

    }

    public function actionPregnant()
    {
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr){
            $userid = EcsUsers::findOne(['open_id'=>$PostArr['userid']])->user_id;
            $reArr = TDetectionPregnant::find()->where(['user_id'=>$userid])->asArray()->limit(3)->orderBy(['create_time'=>SORT_DESC])->all();
        }
        return json_encode($reArr);
    }

    public function actionSetpregnant()
    {
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr) {
            $userid = EcsUsers::findOne(['open_id' => $PostArr['userid']])->user_id;
            $model = new TDetectionPregnant();
            $model->user_id = $userid;
            $model->group_date = date("Y-m-d",time());
            $model->category = "孕检";
            $model->pre = (int)$PostArr['DetectionResult'];
            if($model->pre==0)
                $model->result = '未怀孕';
            else  if($model->pre==1)
                $model->result = '已怀孕';
            else
                $model->result = '检测错误';
            $model->source_data = '检测数据';
            $model->create_time = date("Y-m-d H:i:s",time());
            $model->status = 1;
            if(!$model->save()){
                print_r($model->errors);exit;
            }
            return json_encode([true]);
        }
    }

    public function actionUrine()
    {
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr){
            $userid = EcsUsers::findOne(['open_id'=>$PostArr['userid']])->user_id;
            $reArr = TDetectionUrine::find()->where(['user_id'=>$userid])->asArray()->limit(3)->orderBy(['create_time'=>SORT_DESC])->all();
            foreach($reArr as $k=>$v) {
                $arrv[0]['n_value'] = $v['leu'];
                $arrv[0]['result'] = $v['leuResult'];
                $arrv[0]['order_sn'] = $v['leuStandard'];

                $arrv[1]['n_value'] = $v['nit'];
                $arrv[1]['result'] = $v['nitResult'];
                $arrv[1]['order_sn'] = $v['nitStandard'];

                $arrv[2]['n_value'] = $v['ubg'];
                $arrv[2]['result'] = $v['ubgResult'];
                $arrv[2]['order_sn'] = $v['ubgStandard'];

                $arrv[3]['n_value'] = $v['pro'];
                $arrv[3]['result'] = $v['proResult'];
                $arrv[3]['order_sn'] = $v['proStandard'];

                $arrv[4]['n_value'] = $v['ph'];
                $arrv[4]['result'] = $v['phResult'];
                $arrv[4]['order_sn'] = $v['phStandard'];

                $arrv[5]['n_value'] = $v['bld'];
                $arrv[5]['result'] = $v['bldResult'];
                $arrv[5]['order_sn'] = $v['bldStandard'];

                $arrv[6]['n_value'] = $v['sg'];
                $arrv[6]['result'] = $v['sgResult'];
                $arrv[6]['order_sn'] = $v['sgStandard'];

                $arrv[7]['n_value'] = $v['ket'];
                $arrv[7]['result'] = $v['ketResult'];
                $arrv[7]['order_sn'] = $v['ketStandard'];

                $arrv[8]['n_value'] = $v['bil'];
                $arrv[8]['result'] = $v['bilResult'];
                $arrv[8]['order_sn'] = $v['bilStandard'];

                $arrv[9]['n_value'] = $v['glu'];
                $arrv[9]['result'] = $v['gluResult'];
                $arrv[9]['order_sn'] = $v['gluStandard'];

                $arrv[10]['n_value'] = $v['vc'];
                $arrv[10]['result'] = $v['vcResult'];
                $arrv[10]['order_sn'] = $v['vcStandard'];

                $reArr[$k]['NJdetetioniData'] = $arrv;
            }
        }
        return json_encode($reArr);

    }

    public function actionSeturine()
    {
        header('Access-Control-Allow-Origin:*');
        header("Access-Control-Allow-Origin", "*");
        header("Access-Control-Allow-Credentials", "true");
        header("Access-Control-Allow-Methods", "*");
        header("Access-Control-Allow-Headers", "Content-Type,Access-Token");
        header("Access-Control-Expose-Headers", "*");

        if($_POST) {
            $urine = new TDetectionUrine();
            $userid = EcsUsers::findOne(['open_id' =>$_POST['userid']])->user_id;
            $newArr = $_POST['NJdetetioniData'];
            $urine->user_id = $userid;
            $urine->category = '尿检';

            $urine->leu = $newArr[0]['n_value'];
            $urine->leuResult = $newArr[0]['result'];
            $urine->leuStandard = $newArr[0]['order_sn'];

            $urine->nit = $newArr[1]['n_value'];
            $urine->nitResult = $newArr[1]['result'];
            $urine->nitStandard = $newArr[1]['order_sn'];

            $urine->ubg = $newArr[2]['n_value'];
            $urine->ubgResult = $newArr[2]['result'];
            $urine->ubgStandard = $newArr[2]['order_sn'];

            $urine->pro = $newArr[3]['n_value'];
            $urine->proResult = $newArr[3]['result'];
            $urine->proStandard = $newArr[3]['order_sn'];

            $urine->ph = $newArr[4]['n_value'];
            $urine->phResult = $newArr[4]['result'];
            $urine->phStandard = $newArr[4]['order_sn'];

            $urine->bld = $newArr[5]['n_value'];
            $urine->bldResult = $newArr[5]['result'];
            $urine->bldStandard = $newArr[5]['order_sn'];

            $urine->sg = $newArr[6]['n_value'];
            $urine->sgResult = $newArr[6]['result'];
            $urine->sgStandard = $newArr[6]['order_sn'];

            $urine->ket = $newArr[7]['n_value'];
            $urine->ketResult = $newArr[7]['result'];
            $urine->ketStandard = $newArr[7]['order_sn'];

            $urine->bil = $newArr[8]['n_value'];
            $urine->bilResult = $newArr[8]['result'];
            $urine->bilStandard = $newArr[8]['order_sn'];

            $urine->glu = $newArr[9]['n_value'];
            $urine->gluResult = $newArr[9]['result'];
            $urine->gluStandard = $newArr[9]['order_sn'];

            $urine->vc = $newArr[10]['n_value'];
            $urine->vcResult = $newArr[10]['result'];
            $urine->vcStandard = $newArr[10]['order_sn'];

            $urine->group_date = date("Y-m-d",time());
            $urine->source_data = '检测数据';
            $urine->create_time = date("Y-m-d H:i:s",time());
            $urine->status = 1;
            if(!$urine->save()){
                print_r($urine->errors);exit;
            }
            return json_encode([true]);
        }
    }

    public function actionHeartrate()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($PostArr){
            $userid = EcsUsers::findOne(['open_id'=>$PostArr['userid']])->user_id;
            $reArr = TDetectionHeartrate::find()->where(['user_id'=>$userid])->asArray()->limit(3)->orderBy(['create_time'=>SORT_DESC])->all();

//            $newArr = array();
//            foreach($reArr as $k=>$v) {
//                $val = base64_decode($v['source_data'],true);
//                $baseArr = explode(",",$val);
//                for($i=0;$i<count($baseArr)/2;$i = $i+2){
//                    $v = $baseArr[$i]*128;
//                    $newArr[] = $v+$baseArr[$i+1];
//
//                }
//                $reArr[$k]['obj_data'] = $newArr;
//            }

            foreach($reArr as $k=>$v) {
                $val = base64_decode($v['source_data'],true);
                $baseArr = explode(",",$val);
                $reArr[$k]['obj_data'] = $baseArr;
            }
        }
        return json_encode($reArr);
    }


    public function actionSetheartrate()
    {
        header('Access-Control-Allow-Origin:*');
        $PostArr = json_decode(array_keys($_POST)[0],true);
        if($_POST) {
            $heartrate = new TDetectionHeartrate();
            $userid = EcsUsers::findOne(['open_id' => $_POST['userid']])->user_id;
            $heartrate->user_id = $userid;
            $heartrate->category = "心电检测";
            $heartrate->heart_rate = $_POST['myxinLPJ'];

            $myxinLResultArray = array_unique($_POST['myxinLResultArray']);
            $str = implode(" ",$myxinLResultArray);
            $heartrate->chartUrl = $str;
            $heartrate->status = 1;
            $heartrate->group_date = date("Y-m-d",time());
            $heartrate->create_time = date("Y-m-d H:i:s",time());

//            $myXinDArray = $_POST['myXinDArray'];
//
//            $newXinDARR = array();
//            foreach($myXinDArray as $v) {
//                $newXinDARR[] = $v/128;
//                $newXinDARR[] = $v%128;
//            }
//
//            $heartrate->source_data = base64_encode(implode(",",$newXinDARR));


            $myXinDArray = $_POST['myXinDArray'];
            $heartrate->source_data = base64_encode(implode(",",$myXinDArray));

            $heartrate->save();
            return json_encode([true,'保持成功']);
        }
    }

    /**
     * 这是一个测试的Api
     * @desc 列举所有的注释格式
     * @param string $user_type |用户类型|yes|其他说明|
     * @param int $sex |性别|no|0:不限 1:男 2:女|
     * @return int status 操作码，0表示成功
     * @return array list 用户列表
     * @return int list[].id 用户ID
     * @return string list[].name 用户名字
     * @return string msg 提示信息
     * @exception 400 参数传递错误
     * @exception 500 服务器内部错误
     *
     */
    public function actionDeleteudata()
    {
        header('Access-Control-Allow-Origin:*');
        $auth = new AuthLib();

        //验证身份
        $timeStamp = $_POST['timeStamp'];
        $randomStr = $_POST['randomStr'];
        $signature = $_POST['signature'];
        $str = $auth -> arithmetic($timeStamp,$randomStr);
        if($str != $signature){
            return json_encode(['code'=>401,'msg'=>'签名错误！']);
        }

        if($_POST) {
            $userid = EcsUsers::find()->where(['open_id' =>$_POST['userid'],'login_type'=>3])->one()->user_id;
//            $userid = EcsUsers::find()->where(['open_id' =>'MDFAMTAwMjQwOTA5QGE5NTVlNTU3NTliaN2QyZDEyOTMzNjE4MGZhN2EzMmMwQDU2NzA0ZThhNmNiaYmJmMjgzMzAxNDZmZDI5MmRjZDFmNTUzYjc0YjNmMDdhNDU4NmQ0ODM4M2Zh','login_type'=>3])->one()->user_id;
            TDetectionHeartrate::deleteAll(['user_id'=>$userid]);
            TDetectionOvulation::deleteAll(['user_id'=>$userid]);
            TDetectionPregnant::deleteAll(['user_id'=>$userid]);
            TDetectionUrine::deleteAll(['user_id'=>$userid]);
        }
        return json_encode(['code'=>200,'msg'=>'检测数据删除成功！']);
    }

}
